import { login, getInfo } from '@/api/sys/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  modules: null,
  menus: null
}

const mutations = {
  setToken: (state, token) => {
    state.token = token
  },
  setName: (state, name) => {
    state.name = name
  },
  setAvatar: (state, avatar) => {
    state.avatar = avatar
  },
  setModules: (state, modules) => {
    state.modules = modules
  },
  setMenus: (state, menus) => {
    state.menus = menus
  }
}

const actions = {
  login ({ commit }, user) {
    return new Promise((resolve, reject) => {
      login(user).then(res => {
        commit('setToken', res.token)
        setToken(res.token)
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(res => {
        commit('setName', res.name)
        commit('setAvatar', res.avatar)
        commit('setModules', res.modules)
        commit('setMenus', res.menus)
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },
  logout ({ commit, state }) {
    return new Promise(resolve => {
      commit('setToken', '')
      commit('setName', '')
      commit('setAvatar', '')
      commit('setModules', null)
      commit('setMenus', null)
      removeToken()
      resolve()
    })
  },
  resetToken ({ commit }) {
    return new Promise(resolve => {
      commit('setToken', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
